package com.siau.SevenBubble.wxapi

import android.app.Activity
import android.os.Bundle
import android.widget.Toast
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import hhm.android.library.LogUtils
import hhm.android.library.bus.Bus
import siau.android.base.SBApplication
import siau.android.library.KeyString


class WXEntryActivity : Activity(), IWXAPIEventHandler {

    /**
     * 从微信启动App
     * @param req
     */
    override fun onReq(req: BaseReq?) {
        LogUtils.d("hhm", "req")
        //获取开放标签传递的extinfo数据逻辑
        if (req!!.type === ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX && req is ShowMessageFromWX.Req) {
            val mediaMsg = req.message
            val extInfo = mediaMsg.messageExt

            LogUtils.d("hhm", "extInfo:$extInfo")
            Toast.makeText(this, "extInfo:$extInfo", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onResp(resp: BaseResp?) {
        LogUtils.d("hhm", "resp")
        when (resp?.type) {
            2 -> {//分享
                when (resp.errCode) {
                    BaseResp.ErrCode.ERR_OK -> {
                        finish()
                    }
                    BaseResp.ErrCode.ERR_AUTH_DENIED -> finish()
                    BaseResp.ErrCode.ERR_USER_CANCEL -> finish()
                    else -> finish()
                }
            }
            1 -> {//登录
                when (resp.errCode) {
                    BaseResp.ErrCode.ERR_OK -> {
                        val code = (resp as SendAuth.Resp).code

                        Bus.getDefault().register(this)
                        Bus.getDefault().post(KeyString.wxLogin + code)
                        Bus.getDefault().unregister(this)

                        finish()
                    }
                    BaseResp.ErrCode.ERR_AUTH_DENIED -> finish()
                    BaseResp.ErrCode.ERR_USER_CANCEL -> finish()
                    else -> finish()
                }
            }
            else -> {
                finish()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SBApplication.api.handleIntent(intent, this)
    }
}